<template>
  <a-page-header>
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form-model ref="roleQueryForm" :model="roleQueryForm" layout="inline">
          <a-row :gutter="48">
            <a-col :md="10" :sm="24">
              <a-form-model-item label="RoleLike">
                <a-input v-model="roleQueryForm.roleLike"  placeholder="请输入角色名称或角色代码或角色描述"/>
              </a-form-model-item>
            </a-col>
            <a-col  :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="submitQueryForm()">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQueryForm('roleQueryForm')">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>

      <a-table :columns="columns" :data-source="data"
               :loading="loading" :rowKey="record => record.roleId"
               @change="handleTableChange">

        <template #title>
          <a-button type="primary" icon="plus-circle" style="margin-left: 10px;" @click="showAddModal">
            新增角色
          </a-button>
          <a-modal
              :title="modal.title"
              :visible="modal.visible"
              :confirm-loading="modal.confirmLoading"
              okText="提交" cancelText="取消"
              @ok="handleModalOk" @cancel="handleModalCancel">

            <a-form-model :model="form" ref="form" @submit="handleModalFormSubmit"
                          :label-col="{span:5}" :wrapper-col="{span:14}" :rules="modal.rules">
              <a-form-model-item label="角色名称" ref="roleName" prop="roleName">
                <a-input v-model="form.roleName" placeholder="角色名称"  />
              </a-form-model-item>

              <a-form-model-item label="角色代码" ref="roleCode" prop="roleCode">
                <a-input v-model="form.roleCode" placeholder="请输入角色代码" >
                  <a-select slot="addonBefore" v-model="preRoleName" style="width: 90px">
                    <a-select-option value="ROLE_">
                      ROLE_
                    </a-select-option>
                  </a-select>
                </a-input>
              </a-form-model-item>
              <a-form-model-item label="角色描述" ref="roleInfo" prop="roleInfo">
                <a-input v-model="form.roleInfo" placeholder="请输入角色描述"  />
              </a-form-model-item>

              <a-form-model-item label="角色排序" ref="sort" prop="sort">
                <a-input-number v-model="form.sort" placeholder="请输入角色排序"  />
              </a-form-model-item>


              <a-form-model-item label="是否启用" ref="status" prop="status">
                <a-radio-group v-model="form.status" button-style="solid">
                  <a-radio-button value="1">
                    启用
                  </a-radio-button>
                  <a-radio-button value="0">
                    禁用
                  </a-radio-button>
                </a-radio-group>
              </a-form-model-item>

            </a-form-model>
          </a-modal>
        </template>

        <a slot="roleName" slot-scope="roleName" >{{ roleName }}</a>


        <span slot="status" slot-scope="status">
           <a-tag :color="status?'green':'volcano'">
            <span v-if="status">启用</span>
             <span v-else>禁用</span>
          </a-tag>
        </span>

        <template #action="record">
          <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
          <a-divider type="vertical" />
          <a-popconfirm
              :title="`确认要删除:${record.roleName}吗?`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDeleteRole(record.roleId)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="danger" shape="circle" icon="delete"/>
          </a-popconfirm>


          <a-divider type="vertical" />
          <a-button type="primary" ghost @click="assignPerm(record)">分配权限</a-button>
        </template>
      </a-table>
      <a-modal :title="auth.permDialogTitle" key="authModal" :width="900"
      :visible="auth.permDialogVisible"
      :confirm-loading="auth.confirmLoading" @cancel="handleAuthCancel"
      :footer="null">
        <a-row>
          <a-col :span="12">
            <multi-tree :key="'menuAuth'+new Date().getTime()"
                :menu-replace-fields="auth.menuReplaceFields"
                :button-name="auth.menuButtonName"
                :tree-data="auth.menuData"
                :default-checked-keys="auth.menuDefaultCheckedKeys"
                :default-expanded-keys="auth.menuDefaultExpandedKeys"
                @handleCheckedKeys="handleMenuCheckedKeys"
            ></multi-tree>
          </a-col>
          <a-col :span="12">
            <multi-tree :key="'apiAuth'+new Date().getTime()"
                :menu-replace-fields="auth.apiReplaceFields"
                :button-name="auth.apiButtonName"
                :tree-data="auth.apiData"
                :default-checked-keys="auth.apiDefaultCheckedKeys"
                :default-expanded-keys="auth.apiDefaultExpandedKeys"
                @handleCheckedKeys="handleApiCheckedKeys"
            ></multi-tree>
          </a-col>
        </a-row>
      </a-modal>
    </a-card>

  </a-page-header>
</template>

<script>

import {getAllRoleList,addRole,updateRole,deleteRole,queryRoleLike} from "@/api/role";
import {findApiCheckedKeys,addRoleApi} from "@/api/api";
import {findMenuCheckedKeys,addRoleMenu} from "@/api/menu";
import MultiTree from "@/components/MultiTree";
import axios from "axios";
const columns = [
  {
    dataIndex: 'roleId',
    key:'roleId',
    title: '角色标识'
  },
  {
    dataIndex: 'roleName',
    key:'roleName',
    title: '角色名称',
    scopedSlots: { customRender: 'roleName' },
  },
  {
    dataIndex: 'roleCode',
    key:'roleCode',
    title: '角色代码'
  },
  {
    title: '角色描述',
    dataIndex: 'roleInfo',
    key:'roleInfo'
  },
  {
    title: '角色排序',
    dataIndex: 'sort',
  },
  {
    title: '用户状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '创建时间',
    key:'createTime',
    dataIndex: 'createTime'
  },
  {
    title: '修改时间',
    key:'updateTime',
    dataIndex: 'updateTime'
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];
const rules = {
  roleName: [
    {required: true, message: '请输入角色名称', trigger: ['blur']},
  ],
  roleCode:[
    {required: true,pattern:'^[a-zA-Z][a-zA-Z0-9]*$', message: '请输入角色代码,英文字母开头,并且只能使用英文和数字', trigger: ['blur','change']}
  ],
  sort: [
    {required: true, message: '请输入角色排序', trigger: ['blur','change']},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'blur'}
  ]
}
export default {
  name: "SystemRole",
  components: {MultiTree},
  data(){
    return{
      columns,
      pagination: {},
      loading:false,
      data:[],
      roleQueryForm:{
        roleLike:'',
        isSubmit:false
      },
      auth:{
        currentRecord:undefined,
        confirmLoading:false,
        handlingRoleId: null,   //当前正在分配权限的角色id，点击行末“分配权限”按钮的时候赋值
        permDialogVisible:false,  //分配权限的弹出框默认不可见
        permDialogTitle:"",   //弹出框标题，点击行末“分配权限”按钮的时候赋值
        menuData:[],     //菜单树数据
        menuReplaceFields:{
          children:'children',
          title:'menuName',
          key:'menuId'
        },  //菜单树数据中的label显示内容字段名称
        menuButtonName:"保存菜单查看权限",  //保存权限按钮的名字
        menuDefaultExpandedKeys:[],  //默认展开节点
        menuDefaultCheckedKeys:[],  //默认勾选节点
        apiData:[],
        apiReplaceFields:{
          children:'children',
          title:'apiName',
          key:'apiId'
        },
        apiButtonName:"保存接口访问权限",
        apiDefaultExpandedKeys:[],
        apiDefaultCheckedKeys:[]
      },
      modal:{
        title:'',
        visible:false,
        confirmLoading: false,
        isDisabled:false,
        passwordSwitch:true,
        rules
      },
      preRoleName:'ROLE_',
      form:{
        roleId:undefined,
        roleName:'',
        roleCode:'',
        roleInfo:'',
        sort:undefined,
        status:undefined
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods:{
    handleAuthCancel(){
      this.auth.permDialogVisible = false
    },
    assignPerm(record){
      this.auth.currentRecord = record
      this.auth.handlingRoleId = record.roleId
      this.auth.permDialogTitle = record.roleName+"角色:权限分配"
      let _this = this
      axios.all([findMenuCheckedKeys(record.roleId), findApiCheckedKeys(record.roleId)])
          .then(axios.spread(function (res1, res2) {
            // 两个请求都执行完成后，进入该函数
            console.log(res1,res2)
            _this.auth.menuData = res1.data.tree
            _this.auth.menuDefaultExpandedKeys = res1.data.expandedKeys
            _this.auth.menuDefaultCheckedKeys = res1.data.checkedKeys
            _this.auth.apiData = res2.data.tree
            _this.auth.apiDefaultExpandedKeys = res2.data.expandedKeys
            _this.auth.apiDefaultCheckedKeys = res2.data.checkedKeys
            _this.auth.permDialogVisible = true;
          }));
    },
    handleMenuCheckedKeys(checkedKeys){
      addRoleMenu({id:this.auth.handlingRoleId,checkedIds:checkedKeys.checked})
          .then(res=> this.handleAuthSuccess(res))
      // this.assignPerm({roleId:this.auth.handlingRoleId})
      // this.auth.permDialogVisible = false;
    },
    handleApiCheckedKeys(checkedKeys){
      addRoleApi({id:this.auth.handlingRoleId,checkedIds:checkedKeys.checked})
          .then(res=> this.handleAuthSuccess(res))
      // this.assignPerm({roleId:this.auth.handlingRoleId})
      // this.auth.permDialogVisible = false;
    },
    handleAuthSuccess(res){
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 8
      })
      this.assignPerm(this.auth.currentRecord)
      // this.assignPerm(this.auth.handlingRoleId)
    },
    handleAuthFiled(err){
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    },

    submitQueryForm(){
      this.roleQueryForm.isSubmit = true
      this.loading = true
      queryRoleLike(this.roleQueryForm.roleLike).then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemRole:submitQueryForm"+err.message)
      }).finally(()=>{
        this.loading = false
      })
    },
    resetQueryForm(formName){
      this.$refs[formName].resetFields();
      if (this.roleQueryForm.isSubmit){
        this.fetch()
      }
      this.roleQueryForm.isSubmit = false
    },
    handleTableChange(pagination, filters, sorter){
      console.log(pagination,filters,sorter)
    },
    fetch(params = {}){
      console.log(params)
      this.loading = true
      getAllRoleList().then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemRole:fetch"+err.message)
      }).finally(()=>{
        this.loading = false
      })
    },
    // add or update Start
    showAddModal(){
      this.modal.title = '新增角色'
      this.modal.visible = true
      this.modal.isDisabled = false;
    },
    showEditModal(record){
      this.modal.title = '修改角色'
      this.modal.visible = true
      this.modal.isDisabled = true;
      let { roleId, roleName, roleCode, roleInfo, sort, status} = record
      roleCode = roleCode.split('_')[1]
      this.form = {
        roleId,
        roleName,
        roleCode,
        roleInfo,
        sort,
        status:status?"1":"0"
      }
    },
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.modal.visible = false
      this.resetForm('form')
    },
    resetForm(formName) {
      this.form = {
        roleId:undefined,
        roleName:'',
        roleCode:'',
        roleInfo:'',
        sort:undefined,
        status:undefined
      }
      this.$refs[formName].resetFields();
    },
    handleModalFormSubmit(){
      this.$refs['form'].validate(valid=>{
        if (valid) {
          let submitData = this.form
          submitData.status = this.form.status === "1"
          submitData.roleCode = this.preRoleName+""+this.form.roleCode
          this.modal.confirmLoading = true
          if (this.modal.isDisabled){
            this.handleUpdateRole(submitData)
          }else {
            this.handleAddRole(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }

      })
    },
    handleUpdateRole(user){
      updateRole(user).then(res=>{
        this.handleSuccess(res)
      }).catch(err=>this.handleFiled(err))
    },
    handleAddRole(user){
      addRole(user).then(res=>{
        this.handleSuccess(res)
      }).catch(err=>this.handleFiled(err))
      this.resetForm('form')
    },
    handleDeleteRole(record){
      // this.$confirm({
      //   title: `确认要删除角色:${record.roleName}?`,
      //   content: '点击确定将进行删除',
      //   onOk() {
      deleteRole(record.roleId).then(res=>{
        this.handleSuccess(res)
      }).catch(err=>this.handleFiled(err))
      //   },
      //   onCancel() {},
      // });
    },
    handleSuccess(res){
      this.modal.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 8
      })
      this.fetch()
    },
    handleFiled(err){
      this.modal.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
    // add or update End
  }
}
</script>

<style lang="less">
.table-page-search-wrapper {

  .ant-form-inline {
    .ant-form-item {
      display: flex;
      margin-bottom: 24px;
      margin-right: 0;

      .ant-form-item-control-wrapper {
        flex: 1 1;
        display: inline-block;
        vertical-align: middle;
      }

      > .ant-form-item-label {
        line-height: 32px;
        padding-right: 8px;
        width: auto;
      }
      .ant-form-item-control {
        height: 32px;
        line-height: 32px;
      }
    }
  }

  .table-page-search-submitButtons {
    display: block;
    margin-bottom: 24px;
    white-space: nowrap;
  }
}
</style>
